package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.sky.properties.AliOssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOssUtil {

    @Autowired
    private AliOssProperties aliOssProperties;

    public String upload(MultipartFile file) throws ClientException, IOException, com.aliyuncs.exceptions.ClientException {
        String bucketName = aliOssProperties.getBucketName();
        String endpoint = aliOssProperties.getEndpoint();

        //在环境变量中获取id和key
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        //用uuid重写文件名
        String originalFilename = file.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(i);
        String filename = "sxroute/" + UUID.randomUUID() + substring;       //文件在oss中的位置

        //创建文件流
        InputStream inputStream = file.getInputStream();
        //将文件上传到oss
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filename, inputStream);//bucket名，文件上传位置
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        PutObjectResult result = ossClient.putObject(putObjectRequest);


        //文件访问路径
        String url =  endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + filename;
        //关闭ossclient
        ossClient.shutdown();

        return url;
    }
}
